from flask import Blueprint, request, jsonify
from models import Homework, Problem, User, db
from utils import format_response, parse_datetime
from decorators import teacher_required, student_required, get_current_user
import json

homeworks_bp = Blueprint('homeworks', __name__)

@homeworks_bp.route('/', methods=['GET'])
@student_required
def get_homeworks():
    """获取所有作业"""
    try:
        homeworks = Homework.query.all()
        return jsonify(format_response([homework.to_dict() for homework in homeworks]))
    except Exception as e:
        return jsonify(format_response(message=str(e), code=500)), 500

@homeworks_bp.route('/<int:homework_id>', methods=['GET'])
@student_required
def get_homework(homework_id):
    """获取指定作业"""
    try:
        homework = Homework.query.get(homework_id)
        if not homework:
            return jsonify(format_response(message="作业不存在", code=404)), 404
        
        homework_data = homework.to_dict()
        
        # 获取作业中的题目详情
        problem_ids = homework_data['problems']
        problems = Problem.query.filter(Problem.id.in_(problem_ids)).all()
        homework_data['problem_details'] = [problem.to_dict() for problem in problems]
        
        return jsonify(format_response(homework_data))
    except Exception as e:
        return jsonify(format_response(message=str(e), code=500)), 500

@homeworks_bp.route('/', methods=['POST'])
@teacher_required
def create_homework():
    """创建作业"""
    try:
        current_user = get_current_user()
        data = request.get_json()
        
        print(f"创建作业请求数据: {data}")
        print(f"当前用户: {current_user}")
        
        title = data.get('title')
        description = data.get('description')
        problems = data.get('problems', [])
        deadline = data.get('deadline')
        course_id = data.get('course_id')
        
        if not title:
            return jsonify(format_response(message="作业标题不能为空", code=400)), 400
        
        if not problems:
            return jsonify(format_response(message="作业必须包含至少一道题目", code=400)), 400
        
        # course_id 处理：如果前端没有提供，创建默认课程或使用第一个可用课程
        if not course_id:
            from models import Course
            # 查找当前用户的第一个课程，或创建默认课程
            user_course = Course.query.filter_by(teacher_id=current_user.id).first()
            if not user_course:
                # 创建默认课程
                default_course = Course(
                    name="默认课程",
                    code="DEFAULT",
                    description="系统自动创建的默认课程",
                    teacher_id=current_user.id
                )
                db.session.add(default_course)
                db.session.flush()  # 立即获取ID但不提交
                course_id = default_course.id
                print(f"创建默认课程: {default_course.to_dict()}")
            else:
                course_id = user_course.id
                print(f"使用现有课程: {user_course.to_dict()}")
        
        # 验证题目是否存在
        problem_ids = [int(pid) for pid in problems]
        existing_problems = Problem.query.filter(Problem.id.in_(problem_ids)).all()
        if len(existing_problems) != len(problem_ids):
            return jsonify(format_response(message="部分题目不存在", code=400)), 400
        
        # 解析截止时间
        deadline_datetime = None
        if deadline:
            deadline_datetime = parse_datetime(deadline)
        
        new_homework = Homework(
            title=title,
            description=description,
            course_id=course_id,
            problems=json.dumps(problem_ids),
            deadline=deadline_datetime,
            teacher_id=current_user.id
        )
        
        print(f"准备创建作业: {new_homework.__dict__}")
        
        db.session.add(new_homework)
        db.session.commit()
        
        result = new_homework.to_dict()
        print(f"作业创建成功: {result}")
        
        return jsonify(format_response(result, "作业创建成功"))
    except Exception as e:
        import traceback
        print(f"创建作业异常: {str(e)}")
        print(f"异常详情: {traceback.format_exc()}")
        db.session.rollback()
        return jsonify(format_response(message=str(e), code=500)), 500

@homeworks_bp.route('/<int:homework_id>', methods=['PUT'])
@teacher_required
def update_homework(homework_id):
    """更新作业"""
    try:
        current_user = get_current_user()
        homework = Homework.query.get(homework_id)
        
        if not homework:
            return jsonify(format_response(message="作业不存在", code=404)), 404
        
        # 检查权限：只有创建者或管理员可以修改
        if homework.teacher_id != current_user.id and current_user.role != 'admin':
            return jsonify(format_response(message="没有权限修改此作业", code=403)), 403
        
        data = request.get_json()
        
        if 'title' in data:
            homework.title = data['title']
        
        if 'description' in data:
            homework.description = data['description']
        
        if 'problems' in data:
            problem_ids = [int(pid) for pid in data['problems']]
            # 验证题目是否存在
            existing_problems = Problem.query.filter(Problem.id.in_(problem_ids)).all()
            if len(existing_problems) != len(problem_ids):
                return jsonify(format_response(message="部分题目不存在", code=400)), 400
            homework.problems = json.dumps(problem_ids)
        
        if 'deadline' in data:
            deadline_datetime = None
            if data['deadline']:
                deadline_datetime = parse_datetime(data['deadline'])
            homework.deadline = deadline_datetime
        
        db.session.commit()
        return jsonify(format_response(homework.to_dict(), "作业更新成功"))
    except Exception as e:
        db.session.rollback()
        return jsonify(format_response(message=str(e), code=500)), 500

@homeworks_bp.route('/<int:homework_id>', methods=['DELETE'])
@teacher_required
def delete_homework(homework_id):
    """删除作业"""
    try:
        current_user = get_current_user()
        homework = Homework.query.get(homework_id)
        
        if not homework:
            return jsonify(format_response(message="作业不存在", code=404)), 404
        
        # 检查权限：只有创建者或管理员可以删除
        if homework.teacher_id != current_user.id and current_user.role != 'admin':
            return jsonify(format_response(message="没有权限删除此作业", code=403)), 403
        
        db.session.delete(homework)
        db.session.commit()
        return jsonify(format_response(message="作业删除成功"))
    except Exception as e:
        db.session.rollback()
        return jsonify(format_response(message=str(e), code=500)), 500

@homeworks_bp.route('/teacher/<int:teacher_id>', methods=['GET'])
@student_required
def get_homeworks_by_teacher(teacher_id):
    """获取指定教师的作业"""
    try:
        homeworks = Homework.query.filter_by(teacher_id=teacher_id).all()
        return jsonify(format_response([homework.to_dict() for homework in homeworks]))
    except Exception as e:
        return jsonify(format_response(message=str(e), code=500)), 500

@homeworks_bp.route('/my-homeworks', methods=['GET'])
@teacher_required
def get_my_homeworks():
    """获取当前教师创建的作业"""
    try:
        current_user = get_current_user()
        homeworks = Homework.query.filter_by(teacher_id=current_user.id).all()
        return jsonify(format_response([homework.to_dict() for homework in homeworks]))
    except Exception as e:
        return jsonify(format_response(message=str(e), code=500)), 500

@homeworks_bp.route('/search', methods=['GET'])
@student_required
def search_homeworks():
    """搜索作业"""
    try:
        keyword = request.args.get('keyword', '')
        teacher_id = request.args.get('teacher_id', '')
        
        query = Homework.query
        
        if keyword:
            query = query.filter(Homework.title.contains(keyword) | Homework.description.contains(keyword))
        
        if teacher_id:
            query = query.filter_by(teacher_id=int(teacher_id))
        
        homeworks = query.all()
        return jsonify(format_response([homework.to_dict() for homework in homeworks]))
    except Exception as e:
        return jsonify(format_response(message=str(e), code=500)), 500
